package com.qqtech.qquan.community.service;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Service;

import com.google.common.collect.Lists;
import com.qqtech.core.frame.dao.BaseDao;
import com.qqtech.core.frame.model.PageKit;
import com.qqtech.core.frame.model.PageOrder;
import com.qqtech.core.frame.service.BaseServiceImpl;
import com.qqtech.qquan.community.cache.CommunityAddrCache;
import com.qqtech.qquan.community.dao.CommunityAddrDao;
import com.qqtech.qquan.community.model.CommunityAddr;
import com.qqtech.qquan.community.model.CommunityAddrQuery;
import com.qqtech.qquan.community.model.CommunityAddrVo;

@Service
public class CommunityAddrServiceImpl extends BaseServiceImpl<CommunityAddr>
		implements CommunityAddrService {
	public static final Logger log = LoggerFactory.getLogger(CommunityAddrServiceImpl.class);
	
	@Resource
	private CommunityAddrDao communityAddrDao;
	@Resource
	private CommunityAddrCache communityAddrCache;

	@Override
	protected BaseDao<CommunityAddr> getBaseDao() {
		return communityAddrDao;
	}

	@Override
	public List<CommunityAddrVo> queryListByParentId(Integer communityId, Integer parentId) {
		if (communityId == null) {
			return Lists.newArrayList();
		}
		if (parentId == null) {
			parentId = 0;
		}
		CommunityAddrQuery communityAddrQuery = new CommunityAddrQuery();
		communityAddrQuery.setCommunityId(communityId);
		communityAddrQuery.setParentId(parentId);
		Pageable pageKit = new PageKit(1,Integer.MAX_VALUE,new PageOrder(Direction.ASC, "id"));
		return communityAddrDao.queryList(communityAddrQuery,pageKit);
	}
	
	@Override
	public List<CommunityAddrVo> queryListByParentIdCache(Integer communityId,Integer parentId) {
		if (communityId == null) {
			return Lists.newArrayList();
		}
		if (parentId == null) {
			parentId = 0;
		}
		return communityAddrCache.get(communityId.toString()+"_"+parentId.toString());
	}

	@Override
	public List<CommunityAddrVo> queryListByChildren(Integer childrenId,
			Integer communityId) {
		List<CommunityAddrVo> list = new ArrayList<CommunityAddrVo>();
		if (childrenId == null || childrenId.intValue() == 0 || communityId == null) {
			return list;
		}
		CommunityAddrVo temp = communityAddrDao.getById(childrenId);
		if (temp != null) {
			list.add(temp);
			if (temp.getParentId().intValue() != 0) {
				List<CommunityAddrVo> tempList = queryListByChildren(temp.getParentId(),communityId);
				if (!tempList.isEmpty()) {
					list.addAll(tempList);
				}
			}
		}
		return list;
	}
	
}